package com.czg.jsonschema2lombokpojo;

import static java.util.Arrays.*;
import static org.apache.commons.lang3.StringUtils.*;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 读取各种协议的URI内容。
 */
public class ContentResolver {

    private static final Set<String> CLASSPATH_SCHEMES = new HashSet<>(asList("classpath", "resource", "java"));
    
    private final ObjectMapper objectMapper;

    public ContentResolver() {
        this(null);
    }

    public ContentResolver(JsonFactory jsonFactory) {
        this.objectMapper = new ObjectMapper(jsonFactory)
                .enable(JsonParser.Feature.ALLOW_COMMENTS)
                .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
    }

    /**
     * 解析给定的URI以读取其内容并将结果解析为JSON。
     * <p>
     * 支持协议：
     * <ul>
     * <li>http/https
     * <li>file
     * <li>classpath/resource/java（所有同义，用于从类路径解析schema）
     * </ul>
     *
     * @param uri
     *            读取schema内容的URI
     * @return 在给定URI处找到的JSON树
     */
    public JsonNode resolve(URI uri) {

        if (CLASSPATH_SCHEMES.contains(uri.getScheme())) {
            return resolveFromClasspath(uri);
        }

        try {
            return objectMapper.readTree(uri.toURL());
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Error parsing document: " + uri, e);
        } catch (IOException e) {
            throw new IllegalArgumentException("Unrecognised URI, can't resolve this: " + uri, e);
        }

    }

    private JsonNode resolveFromClasspath(URI uri) {

        String path = removeStart(removeStart(uri.toString(), uri.getScheme() + ":"), "/");
        InputStream contentAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);

        if (contentAsStream == null) {
            throw new IllegalArgumentException("Couldn't read content from the classpath, file not found: " + uri);
        }

        try {
            return objectMapper.readTree(contentAsStream);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Error parsing document: " + uri, e);
        } catch (IOException e) {
            throw new IllegalArgumentException("Unrecognised URI, can't resolve this: " + uri, e);
        }
    }

}
